import json

import redis
from pandas.io.json import json_normalize
from sqlalchemy import create_engine
import pandas as pd

pool = redis.ConnectionPool(host='10.2.111.66', port=6379, db=3,
                            decode_responses=False,password='ehl1234')
# pool = redis.ConnectionPool(host='10.2.111.66', port=6379, db=0,password='ehl1234')
cache = redis.Redis(connection_pool=pool)


def set(key, value):
    cache.set(key, value.to_msgpack(compress='zlib'))
    return


def get(key):
    df = cache.get(key)
    if df is not None:
        return pd.read_msgpack(df)
    else:
        return df


def get_oracle_engine():
    user = 'ehl_sce'
    password = 'ehl1234'
    ip = '10.2.113.84'
    port = '1521'
    instance = 'orcl'
    engine_str = 'oracle://%s:%s@%s:%s/%s' % (user, password, ip, port, instance)
    engine = create_engine(engine_str, encoding='utf-8')
    return engine


def get_data():
    f = open("E:/EHL/CODE/python/项目/信控/数据/basic_data/heze_signal_data_20170927.csv",encoding='utf-8')
    # f = open("E:/EHL/CODE/python/项目/信控/数据/basic_data/heze_cross_topo.csv")

    df = pd.read_csv(f)
    # set('T_SCE_SEGINFO', df)
    set('signal_data',df)
    print('ok')


def savepd_oracle():
    f = open("E:/EHL/CODE/python/项目/信控/数据/basic_data/heze_cross_topodb.csv")
    df = pd.read_csv(f)
    df['ROADSEGNAME'] = df['START'] + df['END']
    df.drop(['START', 'END'], axis=1, inplace=True)
    df.to_sql('t_sce_seginfo_heze', get_oracle_engine(), if_exists='append',
              index=False)
    pass

def clear():
    list = [b'flowtime',b'signal_data',b'tempdata',b'traveltime_df']
    keys = cache.keys()
    for key in keys:
        if key not in list:
            # print(key)
            cache.delete(key)

def redis_list():
    def load(data):
        for i in data:
            yield json.loads(i)
    data = cache.lrange('test',0,-1)
    s = [json.loads(i) for i in data]
    df = json_normalize(s)
    set('df',df)
    print('ok')


if __name__ == '__main__':
    # savepd_oracle()
    # redis_list()
    cache.set('a','b')
    print(cache.get('a')=='b')
    # get_data()